# coding=utf-8
import json
import re, os, time, codecs
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import QUrl, pyqtSignal, pyqtProperty, pyqtSlot, Qt
from PyQt5.QtGui import *
from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineProfile
from PyQt5.QtWidgets import QWidget, QMessageBox
from loguru import logger
from auto_ui.webview import Ui_Form
from huza.base.dockview import DockView

from util.constant import VIEW_URL


class Webshared(QWidget):
    Sig_js_name_chaged = pyqtSignal(str)  # 把值从Shared返回到Wigdet
    Sig_js_getname = pyqtSignal(str)  # 把值从Shared返回到Wigdet
    Sig_Send_SetNameView_ToJS = pyqtSignal(str)  # pyqt触发js信号
    Sig_Get_Name_ToJS = pyqtSignal()  # pyqt触发js获取信号

    def __init__(self):
        super().__init__()

    @pyqtSlot(str)  # 此处必须要写pyqtSlot
    def sig_Recv_Send_SetPyqtview_FromJS(self, js_name_str):  # 接收JS传入的值
        self.Sig_js_name_chaged.emit(js_name_str)

    @pyqtSlot(str)
    def sig_Recv_Get_Value_FromJS(self, js_name_str):  # 接收JS传入的值
        self.Sig_js_getname.emit(js_name_str)


class WebView_Form(Ui_Form, DockView):

    def setupUi(self, Form):
        self.form = Form
        super(WebView_Form, self).setupUi(Form)
        self.load()
        self.connect()
        self.flowdata = None

    def load(self):
        browser = QWebEngineView()
        browser.setContextMenuPolicy(Qt.NoContextMenu)  # 禁用右键
        browser.load(QUrl(VIEW_URL))
        self.browser = browser
        browser.page().profile().setHttpCacheType(QWebEngineProfile.NoCache)  # 禁用缓存
        browser.page().profile().setPersistentCookiesPolicy(QWebEngineProfile.NoPersistentCookies)  # 禁用cookiess
        self.channel = QWebChannel()
        self.shared = Webshared()
        self.shared.Sig_js_name_chaged.connect(self.js_name_change)
        self.shared.Sig_js_getname.connect(self.get_js_name)
        self.channel.registerObject("webchared", self.shared)  # 此处的名字必须与channel.objects.webchared对应
        browser.page().setWebChannel(self.channel)
        browser.loadFinished.connect(self.loadfinish)
        self.widget_web.layout().addWidget(self.browser)

    def loadfinish(self, ok):
        if not ok:
            self.browser.load(QUrl(VIEW_URL))

    def js_name_change(self, txt):
        self.lineEdit_name.setText(txt)

    def get_js_name(self, txt):
        QMessageBox.information(self.form, 'js值获取成功', f'获取到的值为: {txt}')

    def connect(self):
        self.lineEdit_name.textChanged.connect(self.name_chaged)
        self.pushButton_getwebname.clicked.connect(self.getwebclicked)

    def getwebclicked(self):
        self.shared.Sig_Get_Name_ToJS.emit()  # 触发信号，使信号传送到js中

    def name_chaged(self, _str):
        self.shared.Sig_Send_SetNameView_ToJS.emit(_str)  # 触发信号，使信号传送到js中
